<template>
    <div class="debug-page">
        <van-nav-bar title="API调试工具" fixed placeholder />

        <div class="debug-content">
            <van-cell-group title="快速诊断">
                <van-cell>
                    <van-button type="primary" block @click="runDiagnostic">
                        运行完整诊断
                    </van-button>
                </van-cell>
                <van-cell>
                    <van-button type="success" block @click="quickTest">
                        快速测试修复
                    </van-button>
                </van-cell>
            </van-cell-group>

            <van-cell-group title="单项测试">
                <van-cell>
                    <van-button @click="checkToken" block>检查Token状态</van-button>
                </van-cell>
                <van-cell>
                    <van-button @click="testPublic" block>测试公开API</van-button>
                </van-cell>
                <van-cell>
                    <van-button @click="testDB" block>测试数据库</van-button>
                </van-cell>
                <van-cell>
                    <van-button @click="testCommunity" block>测试社区API</van-button>
                </van-cell>
            </van-cell-group>

            <van-cell-group title="日志输出">
                <div class="log-container">
                    <pre>{{ logs }}</pre>
                </div>
            </van-cell-group>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { showToast } from 'vant'

const logs = ref('')

const addLog = (message: string) => {
    const timestamp = new Date().toLocaleTimeString()
    logs.value += `[${timestamp}] ${message}\n`
}

const checkToken = () => {
    const token = localStorage.getItem('token')
    const user = localStorage.getItem('user')

    addLog(`Token: ${token ? '存在' : '不存在'}`)
    addLog(`User: ${user ? '存在' : '不存在'}`)

    if (token) {
        addLog(`Token前20字符: ${token.substring(0, 20)}...`)
    }
}

const testPublic = async () => {
    addLog('开始测试公开API...')

    try {
        const response = await fetch('/api/v1/test/ping', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })

        addLog(`公开API响应状态: ${response.status}`)

        if (response.ok) {
            const data = await response.json()
            addLog(`公开API响应: ${JSON.stringify(data, null, 2)}`)
        } else {
            const errorText = await response.text()
            addLog(`公开API错误: ${errorText}`)
        }
    } catch (error) {
        addLog(`公开API请求失败: ${error}`)
    }
}

const testDB = async () => {
    addLog('开始测试数据库连接...')

    const token = localStorage.getItem('token')
    if (!token) {
        addLog('错误: 没有token')
        return
    }

    try {
        const response = await fetch('/api/v1/test/database', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })

        addLog(`数据库测试响应状态: ${response.status}`)

        if (response.ok) {
            const data = await response.json()
            addLog(`数据库测试响应: ${JSON.stringify(data, null, 2)}`)
        } else {
            const errorText = await response.text()
            addLog(`数据库测试错误: ${errorText}`)
        }
    } catch (error) {
        addLog(`数据库测试请求失败: ${error}`)
    }
}

const testCommunity = async () => {
    addLog('开始测试社区API...')

    const token = localStorage.getItem('token')
    if (!token) {
        addLog('错误: 没有token')
        return
    }

    try {
        const response = await fetch('/api/v1/community/shares?page=1', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })

        addLog(`社区API响应状态: ${response.status}`)
        addLog(`响应头: ${JSON.stringify(Object.fromEntries(response.headers.entries()), null, 2)}`)

        if (response.ok) {
            const data = await response.json()
            addLog(`社区API响应: ${JSON.stringify(data, null, 2)}`)
        } else {
            const errorText = await response.text()
            addLog(`社区API错误响应: ${errorText}`)
        }
    } catch (error) {
        addLog(`社区API请求失败: ${error}`)
    }
}

const runDiagnostic = async () => {
    logs.value = ''
    addLog('开始完整诊断...')

    checkToken()
    await testPublic()
    await testDB()
    await testCommunity()

    addLog('诊断完成!')
    showToast('诊断完成，请查看日志')
}

const quickTest = async () => {
    logs.value = ''
    addLog('快速测试修复结果...')

    // 只测试关键的API
    await testDB()
    await testCommunity()

    addLog('快速测试完成!')
    showToast('测试完成')
}
</script>

<style lang="scss" scoped>
.debug-page {
    min-height: 100vh;
    background: #f7f8fa;

    .debug-content {
        padding: 16px;

        .log-container {
            background: #000;
            color: #0f0;
            padding: 12px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 400px;
            overflow-y: auto;

            pre {
                margin: 0;
                white-space: pre-wrap;
                word-wrap: break-word;
            }
        }
    }
}
</style>